﻿using System;
using System.Runtime.InteropServices;

namespace XiaoSe.Windows.Forms
{
    public class WinHotKey
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="fsModifiers">Alt = 0x1,Ctrl = 0x2,Shift = 0x4,Win = 0x8,组合键等于值相加Alt_Ctrl = 0x3,Alt_Shift = 0x5,Ctrl_Shift = 0x6,Alt_Ctrl_Shift = 0x7</param>
        /// <param name="vk"></param>
        /// <returns></returns>
        public static UInt32 RegisterHotKeyA(IntPtr hWnd, UInt32 fsModifiers, UInt32 vk)
        {
            UInt32 uKeyId = GlobalAddAtom(new Guid().ToString());
            if (uKeyId == 0)
            {
                return 0;
            }
            UInt32 iResult = RegisterHotKey(hWnd, uKeyId, fsModifiers, vk);
            return iResult == 0 ? 0 : uKeyId;
        }
        public static bool UnregisterHotKeyA(IntPtr hWnd, UInt32 id)
        {
            UInt32 iResult = UnregisterHotKey(hWnd, id);
            if (iResult == 0)
            {
                return false;
            }
            GlobalDeleteAtom(id);
            return true;
        }

        [DllImport("user32.dll")]
        private static extern UInt32 RegisterHotKey(IntPtr hWnd, UInt32 id, UInt32 fsModifiers, UInt32 vk);
        [DllImport("user32.dll")]
        private static extern UInt32 UnregisterHotKey(IntPtr hWnd, UInt32 id);
        [DllImport("kernel32.dll")]
        private static extern UInt32 GlobalAddAtom(String lpString);
        [DllImport("kernel32.dll")]
        private static extern UInt32 GlobalDeleteAtom(UInt32 nAtom);
    }
}
